<?php
    /**
     * Created by PhpStorm.
     * User: mybook-lhp
     * Date: 18/7/12
     * Time: 下午4:49
     */

    namespace app\payment\admin;


    use app\common\builder\ZBuilder;
    use app\member\model\MemberModel;
    use app\payment\model\PaymentWithdrawModel;

    use think\Db;

    /**
     * 提现手续费
     * Class Withdrawratio
     *
     * @package app\sharechain\admin
     */
    class Withdrawratio extends PaymentBase
    {

        public function index($status = null)
        {

            // 查询
            $map = $this->getMap();

            if ($status !== null)
            {
                $map['payment_withdraw.status'] = $status;
            }
            if (isset($map['create_time']))
            {
                $map ["payment_withdraw.create_time"] = $map ["create_time"];
                unset ($map ["create_time"]);
            }
            if (isset($map['update_time']))
            {
                $map ["payment_withdraw.update_time"] = $map ["update_time"];
                unset ($map ["update_time"]);
            }
            if (isset($map['phone']))
            {

                $MemberModel      = MemberModel::where(['phone' => $map ["phone"]])->find();
                $map["member.id"] = $MemberModel["id"];
                unset ($map ["phone"]);
            }

            // 排序
            $order = $this->getOrder('update_time desc');
            //检查权限
            $list_auth    = check_auth_node(UID,'group',self::AUTH_GUADAN_WITHMONEY_LIST);
            $right_button = [];
            if ($list_auth)
            {
                $map['payment_withdraw.update_time'] = ['gt',strtotime(self::GROUP_TIEMS)];
                $right_button                        = ['right_button','操作','btn'];
            }

            // 数据列表
            $data_list = Db::view('payment_withdraw',true)//字段
            ->view('member','phone','member.id = payment_withdraw.member_id')//
            ->where($map)//
            ->order($order)//
            ->paginate();


            // 使用ZBuilder快速创建数据表格
            return ZBuilder::make('table')//
            ->addTimeFilter('create_time')// 添加时间段筛选
            ->addTopButton('back')//
            ->setSearchArea([
                ['text','phone','用户'],
                ['text','order_sn','订单编号'],
                ['daterange','create_time','创建时间','','',['min-date' => '2018-10-10']],
                ['daterange','update_time','修改时间','','',['min-date' => '2018-10-10']],
            ])->addColumns($this->addColumns_group($list_auth))//
            ->addTopButtons($this->addTopButtons_group($list_auth,$status))// 批量添加顶部按钮
            ->addRightButtons($this->addRightButtons_group($list_auth,$status))// 批量添加右侧按钮
            ->addOrder('type,create_time,amount_money')//排序
            ->setRowList($data_list)// 设置表格数据
            ->fetch(); // 渲染模板
        }

        public function addColumns_group($group = false)
        {

            if ($group)
            {
                $data = [ // 批量添加数据列
                          ['id','ID'],
                          //['phone','用户','text'],

                          ['phone','用户','text'],
                          ['type','支付方式','text','',[1 => '微信',2 => '支付宝',3 => '银行卡']],

                          ['amount_money','提现总额','callback','view_money'],
                          ['proc_fee','提现手续费','callback','view_money'],
                          ['true_money','实际到账','callback','view_money'],
                          ['status','状态','status','',[0 => '待审核',1 => '审核驳回',2 => '审通过',3 => '撤单',4 => '审核中',]],
                          //                             ['pass','是否可提','status','',[0 => '待审核',1 => '审核驳回',2 => '审通过',3 => '撤单',4 => '审核中',]],
                          //                             ['create_time','创建时间','datetime','','Y/m/d H:i:s'],
                          ['create_time','提交时间','datetime','','Y/m/d H:i:s'],
                          ['update_time','更新时间','datetime','','Y/m/d H:i:s'],
                          //                             ['order_sn','订单编号','text'],
                          //                          ['right_button','操作','btn'],

                ];
            }
            else
            {
                $data = [ // 批量添加数据列
                          ['id','ID'],
                          //['phone','用户','text'],

                          ['phone','用户','link',url('member/index/view',['id' => '__member_id__'])],
                          ['type','支付方式','text','',[1 => '微信',2 => '支付宝',3 => '银行卡']],
                          [
                              'type',
                              '账号',
                              'callback',
                              function ($value,$data)
                              {

                                  if ($data['type'] == '微信')
                                  {
                                      return $data['wxpay_name'] . ':<br>' . $data['wxpay_account'];
                                  }
                                  if ($data['type'] == '支付宝')
                                  {
                                      return $data['aliplay_name'] . ':<br>' . $data['aliplay_account'];
                                  }
                                  $url = url('view',['id' => $data['id']]);
                                  if ($data['type'] == '银行卡')
                                  {

                                      return "<a href='{$url}'>点击查看账号</a>";
                                  }
                                  return "<a href='{$url}'>点击查看账号</a>";
                              },
                              '__data__'
                          ],
                          ['amount_money','提现总额','callback','view_money'],
                          ['proc_fee','提现手续费','callback','view_money'],
                          ['true_money','实际到账','callback','view_money'],
                          ['status','状态','status','',[0 => '待审核',1 => '审核驳回',2 => '审通过',3 => '撤单',4 => '审核中',]],
                          //                             ['pass','是否可提','status','',[0 => '待审核',1 => '审核驳回',2 => '审通过',3 => '撤单',4 => '审核中',]],
                          //                             ['create_time','创建时间','datetime','','Y/m/d H:i:s'],
                          ['create_time','提交时间','datetime','','Y/m/d H:i:s'],
                          ['update_time','更新时间','datetime','','Y/m/d H:i:s'],
                          //                             ['order_sn','订单编号','text'],
                          ['right_button','操作','btn'],

                ];
            }
            return $data;
        }

        /**
         *
         * @param bool $list_auth
         *
         * @return array
         */
        public function addTopButtons_group($list_auth = false,$status = null)
        {

            //            echo json_encode($map);
            //            exit;
            if ($list_auth)
            {
                $data = [
                    'status'  => [
                        'title' => '所有',
                        'href'  => url('index')
                    ],
                    'status0' => [
                        'title' => '待审核',
                        'href'  => url('index',['status' => 0])
                    ],
                    'status1' => [
                        'title' => '审核中',
                        'href'  => url('index',['status' => 4])
                    ],
                    'status2' => [
                        'title' => '审核驳回',
                        'href'  => url('index',['status' => 1])
                    ],
                    'status3' => [
                        'title' => '审通过',
                        'href'  => url('index',['status' => 2])
                    ],
                    'status4' => [
                        'title' => '撤单',
                        'href'  => url('index',['status' => 3])
                    ],

                ];
            }
            else
            {
                $data = [
                    'status'  => [
                        'title' => '所有',
                        'href'  => url('index')
                    ],
                    'status0' => [
                        'title' => '待审核',
                        'href'  => url('index',['status' => 0])
                    ],
                    'status1' => [
                        'title' => '审核中',
                        'href'  => url('index',['status' => 4])
                    ],
                    'status2' => [
                        'title' => '审核驳回',
                        'href'  => url('index',['status' => 1])
                    ],
                    'status3' => [
                        'title' => '审通过',
                        'href'  => url('index',['status' => 2])
                    ],
                    'status4' => [
                        'title' => '撤单',
                        'href'  => url('index',['status' => 3])
                    ],
                    'Excel'   => [
                        'title' => '导出Excel',
                        'href'  => url('excel',['status' => $status])
                    ],
                ];
            }

            return $data;
        }

        public function addRightButtons_group($list_auth = false,$status)
        {

            if (!$list_auth)
            {
                if ($status === "0")
                {
                    $data = [
                        'view'    => [
                            'title' => '查看账号',
                            'icon'  => 'fa fa-fw fa-vcard-o',
                            'class' => 'btn btn-xs btn-default',
                            'href'  => url('view',['id' => '__id__'])
                        ],
                        'status1' => [
                            'title' => '审核中',
                            'icon'  => 'fa fa-fw fa-flag-checkered',
                            'class' => 'btn btn-xs btn-default ajax-get confirm',
                            'href'  => url('status',['id' => '__id__','status' => 4])
                        ],
                    ];
                }
                elseif ($status == 4)
                {
                    $data = [
                        'view' => [
                            'title' => '查看账号',
                            'icon'  => 'fa fa-fw fa-vcard-o',
                            'class' => 'btn btn-xs btn-default',
                            'href'  => url('view',['id' => '__id__'])
                        ],

                        'check' => [
                            'title' => '审核',
                            'icon'  => 'fa fa-fw fa-thumbs-up',
                            'class' => 'btn btn-xs btn-default',
                            'href'  => url('check',['id' => '__id__'])
                        ],
                        //                    'status2' => [
                        //                        'title' => '审核通过',
                        //                        'icon'  => 'fa fa-fw fa-thumbs-up',
                        //                        'class' => 'btn btn-xs btn-default ajax-get confirm',
                        //                        'href'  => url('status',['id' => '__id__','status' => 2])
                        //                    ],
                        //                    'status1' => [
                        //                        'title' => '审核驳回',
                        //                        'icon'  => 'fa fa-fw fa-thumbs-down',
                        //                        'class' => 'btn btn-xs btn-default ajax-get confirm',
                        //                        'href'  => url('status',['id' => '__id__','status' => 1])
                        //                    ],
                        //                    'status3' => [
                        //                        'title' => '撤单',
                        //                        'icon'  => 'fa fa-fw fa-trash',
                        //                        'class' => 'btn btn-xs btn-default ajax-get confirm',
                        //                        'href'  => url('status',['id' => '__id__','status' => 3])
                        //                    ],
                    ];
                }
                else
                {
                    $data = [];
                }
            }
            else
            {
                $data = [];
            }

            return $data;
        }

        public function Excel($status = null)
        {

            // 查询
            //            $map = $this->getMap();
            $map = [];
            if (!isset($map['status']))
            {
                $map['payment_withdraw.status'] = $status;
            }

            if (isset($map['create_time']))
            {
                $map ["payment_withdraw.create_time"] = $map["create_time"];
                unset ($map ["create_time"]);
            }
            if (isset($map['update_time']))
            {
                $map ["payment_withdraw.update_time"] = $map["update_time"];
                unset ($map ["update_time"]);
            }
            if (isset($map['phone']))
            {
                $MemberModel      = MemberModel::where(['phone' => $map["phone"]])->find();
                $map["member.id"] = $MemberModel["id"];
                unset ($map ["phone"]);
            }

            $data = [];
            $list = Db::view('payment_withdraw',true)//字段
            ->view('member','phone','member.id = payment_withdraw.member_id','left')->where($map)->select();

            if ($list)
            {
                foreach ($list as $key => $iem)
                {
                    if ($iem['type'] == 2)
                    {
                        $type = '支付宝';
                        $name = $iem['aliplay_name'];
                        $nub  = $iem['aliplay_account'];
                    }
                    else
                    {
                        $type = '银行卡';
                        $name = $iem['bank_ture_name'];
                        $nub  = $iem['bank_name'] . ' :' . $iem['bank_card_number'];
                    }
                    if ($iem['status'] == 0)
                    {
                        $status = '待审核';
                    }
                    else if ($iem['status'] == 1)
                    {
                        $status = '驳回';
                    }
                    else if ($iem['status'] == 2)
                    {
                        $status = '通过';
                    }
                    else if ($iem['status'] == 3)
                    {
                        $status = '撤单';
                    }
                    else if ($iem['status'] == 4)
                    {
                        $status = '审核中';
                    }

                    //审核状态0审核中1审核失败2审通过3撤单
                    $data[$key]['phone']        = $iem['phone'];
                    $data[$key]['update_time']  = date("Y-m-d H:i:s",$iem['update_time']);
                    $data[$key]['create_time']  = date("Y-m-d H:i:s",$iem['create_time']);
                    $data[$key]['status']       = $status;
                    $data[$key]['name']         = $name;
                    $data[$key]['member_id']    = $iem['member_id'];
                    $data[$key]['nub']          = $nub;
                    $data[$key]['type']         = $type;
                    $data[$key]['amount_money'] = round($iem['amount_money'] / 100,2);
                    $data[$key]['proc_fee']     = round($iem['proc_fee'] / 100,2);
                    $data[$key]['true_money']   = round($iem['true_money'] / 100,2);
                }
            }

            //            echo json_encode($data);
            //            exit;
            // 查询数据

            // 设置表头信息（对应字段名,宽度，显示表头名称）
            $cellName = [
                ['member_id','auto','用户ID'],
                ['phone','auto','手机号码'],
                ['type','auto','提现方式'],
                ['name','auto','姓名'],
                ['nub','auto','账号'],
                ['amount_money','auto','提现总额'],
                ['proc_fee','auto','提现手续费 '],
                ['true_money','auto','实际到账 '],
                ['status','auto','状态  '],
                ['create_time','auto','提交时间  '],
                ['update_time','auto','更新时间  '],
            ];
            $time     = date("Y-m-d H:i:s",time());
            // 调用插件（传入插件名，[导出文件名、表头信息、具体数据]）
            plugin_action('Excel/Excel/export',[$time . '提现',$cellName,$data]);

        }

        public function status($id = null,$status = null)
        {

            if ($status !== null && $id !== null)
            {
                return PaymentWithdrawModel::update(['status' => $status],['id' => $id]) ? $this->success('操作成功！') : $this->error('操作失败！');
            }
            $this->error('参数错误！');
        }

        /**
         * @return mixed
         * @throws \think\Exception
         */
        public function view($id = null)
        {

            if ($id === null)
                $this->error('参数错误！');
            $type                 = [1 => '微信',2 => '支付宝',3 => '银行卡'];
            $data                 = PaymentWithdrawModel::get($id);
            $data['type']         = $type[$data['type']];
            $data['amount_money'] = $data['amount_money'] / 100;
            $data['proc_fee']     = $data['proc_fee'] / 100;
            $data['true_money']   = $data['true_money'] / 100;

            // 显示添加页面
            return ZBuilder::make('form')->addFormItems([

                ['static','order_sn','订单编号'],
                ['static','type','支付方式',''],
                ['static','amount_money','提现总额',''],
                ['static','proc_fee','手续费',''],
                ['static','true_money','实际金额',''],
                ['static','wxpay_name','微信真实姓名',''],
                ['static','wxpay_account','微信账号',''],
                ['static','aliplay_name','支付宝真实姓名',''],
                ['static','aliplay_account','支付宝真实姓名',''],
                ['static','bank_name','银行名称',''],
                ['static','bank_card_number','银行卡号码',''],
                ['static','bank_ture_name','持卡人姓名',''],
                ['static','create_time','下单时间',''],
            ])->setFormData($data)->fetch();
        }

        /**
         * 审核操作
         *
         * @return mixed
         * @throws \think\Exception
         */
        public function check($id = null)
        {

            if ($id === null)
                $this->error('缺少参数！');

            // 保存数据
            if ($this->request->isPost())
            {
                // 表单数据
                $data = $this->request->post();
                $data = $this->check_validate($data,'Withdrawratio.check');
                //审核驳回并返回提现金额
                if ($data['status'] === '1')
                {
                    $res = PaymentWithdrawModel::backout($data['order_sn'],1);
                }
                else
                {
                    $res = PaymentWithdrawModel::update($data,['order_sn' => $data['order_sn']]);
                }

                //审核通过
                $res ? $this->success('提交成功','index') : $this->error('提交失败');
                die;
            }

            $type                 = [1 => '微信',2 => '支付宝',3 => '银行卡'];
            $data                 = PaymentWithdrawModel::get($id);
            $data['type']         = $type[$data['type']];
            $data['amount_money'] = $data['amount_money'] / 100;
            $data['proc_fee']     = $data['proc_fee'] / 100;
            $data['true_money']   = $data['true_money'] / 100;

            // 显示添加页面
            return ZBuilder::make('form')->addFormItems([
                ['static','order_sn','订单编号','','',true],
                ['static','type','支付方式',''],
                ['static','amount_money','提现总额',''],
                ['static','proc_fee','手续费',''],
                ['static','true_money','实际金额',''],
                ['static','wxpay_name','微信真实姓名',''],
                ['static','wxpay_account','微信账号',''],
                ['static','aliplay_name','支付宝真实姓名',''],
                ['static','bank_name','银行名称',''],
                ['static','bank_card_number','银行卡号码',''],
                ['static','bank_ture_name','持卡人姓名',''],
                ['textarea','admin_remarks','管理员备注',''],
                ['static','create_time','下单时间',''],
                ['select','status','状态','',[1 => '审核驳回',2 => '审通过',]]
            ])->setFormData($data)->fetch();
        }

    }